package com.ciwong.epaper.modules.wordlist;

import android.content.Intent;
import android.os.Handler;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.ciwong.epaper.R;
import com.ciwong.epaper.modules.wordlist.bean.WordAnswerList;
import com.ciwong.epaper.modules.wordlist.dao.WorkBookDao;
import com.ciwong.epaper.util.BaseExtCallBack;
import com.ciwong.epaper.util.DialogUtil;
import com.ciwong.epaper.util.FeedbackUtil;
import com.ciwong.epaper.util.IntentFlag;
import com.ciwong.libs.utils.NetworkUtils;
import com.ciwong.mobilelib.i.GoBackListener;
import com.ciwong.mobilelib.utils.ToastUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.unisound.edu.oraleval.sdk.sep15.IOralEvalSDK;
import com.unisound.edu.oraleval.sdk.sep15.SDKError;

import java.util.List;

/**
 * 单词练习界面
 * Created by young on 2018/3/27.
 */

public class WordListReadActivity extends BaseWordlistActivity
        implements BaseWordListReadController.OnSpeechListener {
    private WordListReadControler wordListReadControler;

    private WordSpeechView wordSpeechView;

    private TextView scoreView,seeScoreView;

    protected RelativeLayout mRlCheckMode;

    private Handler mHandler = new Handler();

    public static final int REQUEST_CODE_FROM_WORD_LIST = 100;

    public static final int REQUEST_CODE_FROM_WORD_LIST_DETAIL = 101;

    @Override
    public void goBack() {
        submitAnswer();
    }

    @Override
    public void play() {
        wordListReadControler.startStudy();
    }

    @Override
    public void pause() {
        if (!wordListReadControler.isPause()) {
            wordListReadControler.pause();
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (!wordListReadControler.isPause()) {
            wordListReadControler.pause();
        }
    }

    @Override
    public void nextWord() {
        wordListReadControler.scoreViewGone();
        if (words != null
                && wordListReadControler.currentListenAndRepeatIndex >= words
                .size() - 1) {
            submitAnswer();
        } else {
            if (NetworkUtils.isOnline()) {
                wordListReadControler.currentListenAndRepeatIndex++;
                play();
            } else {
                ToastUtil.INSTANCE.toastCenterNoNetError();
            }
        }

    }

    @Override
    public void repeatWord() {
        wordListReadControler.scoreViewGone();
        if (NetworkUtils.isOnline()) {
            play();
        } else {
            ToastUtil.INSTANCE.toastCenterNoNetError();
        }

    }

    @Override
    protected int setView() {
        return R.layout.word_list_read;
    }

    @Override
    protected void findViews() {
        super.findViews();
        wordSpeechView = findViewById(R.id.unitSpeech);
        scoreView = findViewById(R.id.tv_show_score);
        seeScoreView = findViewById(R.id.tv_see_score);
        mRlCheckMode = findViewById(R.id.rl_check_mode);
    }

    @Override
    protected void init() {
        super.init();
        setTitleText("单词跟读练习");
        setGoBackListener(new GoBackListener() {
            @Override
            public void goBack() {
                submitAnswer();
            }
        });
        mRlCheckMode.setVisibility(View.GONE);
    }

    @Override
    protected void loadData() {
        try {
            initYzs();
            initData();
            wordListReadControler.currentListenAndRepeatIndex = 0;
            refreshWordUi(0);
            play();
        } catch (Exception e) {
            e.getStackTrace();
        }
    }

    /**
     * 初始化数据
     */
    private void initData() {
        wordListReadControler.setPlayAssess(isPlayAssess);
        wordListReadControler.setUnitWord(words, read_bottom_view, scoreView,seeScoreView,
                getUserInfoBase().getUserId());
        wordListReadControler.setOnUnitSpeechListener(this);
        wordListReadControler.setRepeatDuration(1000);
        wordListReadControler.setReadDuration(1000);
    }

    /**
     * 刷新显示单词界面
     */
    private void refreshWordUi(int currPoint) {
        wordSpeechView.setVisibility(View.VISIBLE);
        setNo(wordListReadControler.currentListenAndRepeatIndex + 1,
                words.size());
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (wordListReadControler != null) {
            wordListReadControler.setPlayAssess(isPlayAssess);
        }
    }

    /**
     * 初始化评测库
     */
    private void initYzs() {
        wordListReadControler = new WordListReadControler(
                WordListReadActivity.this, wordSpeechView,serviceExpired);
    }

    public void submitAnswer() {

        if (!NetworkUtils.isOnline()) {
            ToastUtil.INSTANCE.toastCenterNoNetError();
        }

        if (!wordListReadControler.isPause()) {
            wordListReadControler.pause();
        }
        showCricleProgress();
        try {
            if (wordListReadControler.answerRecorders == null) {
                hideCricleProgress();
                return;
            }
            // 生成userAnswer.json
            Gson gson = new Gson();
            String userAnswerJson = gson.toJson(
                    wordListReadControler.answerRecorders,
                    new TypeToken<List<WordAnswerList>>() {
                    }.getType());
            WorkBookDao.getInstance().submitWordReadWork(userAnswerJson,
                    new BaseExtCallBack(WordListReadActivity.this,
                            getUserInfoBase().getUserId() + "") {
                        @Override
                        public void success(Object data) {// try

                            if (mRequestFrom == REQUEST_CODE_FROM_WORD_LIST_DETAIL) {
                                Intent intent = new Intent();
                                if (wordListReadControler.answerRecorders != null
                                        && wordListReadControler.answerRecorders
                                        .size() > 0) {
                                    intent.putExtra(
                                            IntentFlag.INTENT_FLAG_ACTUAL_SCORE,
                                            wordListReadControler.answerRecorders
                                                    .get(0).getScore());
                                    intent.putExtra(
                                            IntentFlag.INTENT_FLAG_EVALUATE_RESULT,
                                            wordListReadControler.answerRecorders
                                                    .get(0).getResult());
                                }
                                setResult(RESULT_OK, intent);
                            }
                            hideCricleProgress();
                            finish();

                        }

                        @Override
                        public void failed(final Object data) {
                            super.failed(data);
                            hideCricleProgress();
                            finish();
                        }

                        @Override
                        public void failed(final int errorCode,
                                           final Object data) {
                            try {
                                super.failed(errorCode, data);
                                hideCricleProgress();
                                if (errorCode != 17 && errorCode != 27) {
                                    finish();
                                }
                            } catch (Exception e) {
                                e.getStackTrace();
                            }

                        }
                    });
        } catch (Exception e) {
            e.getStackTrace();
        }

    }

    @Override
    public void onListenerComplete() {

    }

    @Override
    public void startRecordAnim() {

    }

    @Override
    public void onComplete(float score) {
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                int index = wordListReadControler.currentListenAndRepeatIndex
                        + 1;
                index = index > words.size() ? words.size() : index;
                setNo(index, words.size());
            }
        });

    }

    @Override
    public void stopRecordAnim() {

    }

    @Override
    public void updateProgress(int total, int progress) {

    }

    @Override
    public void recError(IOralEvalSDK evalSDK, final SDKError sdkError,
                         IOralEvalSDK.OfflineSDKError offlineSDKError) {
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                SDKError.Category category = sdkError.category;
                if (SDKError.Category.Network == category) {
                    if (!NetworkUtils.isOnline()) {
                        ToastUtil.INSTANCE.toastCenterNoNetError();
                    } else {
                        ToastUtil.INSTANCE.toastCenterError(
                                "评分过程遇到错误，错误信息：" + sdkError.errno);
                    }
                } else if (SDKError.Category.Device == category) {
                    DialogUtil
                            .showSettingPermissions(WordListReadActivity.this);
                } else {
                    ToastUtil.INSTANCE.toastCenterError(
                            "评分过程遇到错误，错误信息：" + sdkError.errno);
                }
            }
        });
        String logDesc = "云之声评分失败###errorCode####" + sdkError.toString();
        FeedbackUtil.getInstance().addFeedbackLog(
                FeedbackUtil.FEEDBACK_TYPE_EVALUATE, logDesc, "评分失败");
    }

    @Override
    public void notFile() {

    }

}
